package com.zhuliwei.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.openai.*;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.openai.api.OpenAiAudioApi;
import org.springframework.ai.openai.api.OpenAiImageApi;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * @author 朱力维
 * @time 2024/11/15 18:11
 **/
@Configuration
public class AiConfig {
    @Value("${spring.ai.openai.api-key}")
    private String apiKey;
    @Value("${spring.ai.openai.base-url}")
    private String baseUrl;
    @Value("${spring.ai.openai.chat.options.model}")
    private String model;

    @Bean
    public ChatClient chatClient() {
        OpenAiApi openAiApi = new OpenAiApi(baseUrl,apiKey);
        OpenAiChatOptions openAiChatOptions = new OpenAiChatOptions();
        openAiChatOptions.setModel(model);
        ChatModel chatModel = new OpenAiChatModel(openAiApi,openAiChatOptions);
        return ChatClient
                .builder(chatModel)
                // 默认角色预设
                .defaultSystem("你现在是Zlwblog技术论坛的智能技术客服小Z，朱力维是这个论坛的主人兼开发者，你对提问用户的称呼要称呼为‘大佬’")
                .build();
    }

    @Bean
    public ChatModel chatModel() {
        OpenAiApi openAiApi = new OpenAiApi(baseUrl, apiKey);
        OpenAiChatOptions openAiChatOptions = new OpenAiChatOptions();
        openAiChatOptions.setModel(model);
//        "你现在是Zlwblog技术论坛的智能技术客服小Z，朱力维是这个论坛的主人兼开发者，你对提问用户的称呼要称呼为‘大佬’"
        ChatModel chatModel = new OpenAiChatModel(openAiApi, openAiChatOptions);
        return chatModel;
    }

    @Bean
    public OpenAiImageModel openaiImageModel() {
        OpenAiImageApi openAiImageApi = new OpenAiImageApi(baseUrl, apiKey, RestClient.builder());
        return new OpenAiImageModel(openAiImageApi);
    }

    @Bean
    public OpenAiAudioSpeechModel openAiAudioSpeechModel() {
        OpenAiAudioApi audioApi = new OpenAiAudioApi(baseUrl, apiKey, RestClient.builder(), WebClient.builder(), RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER);
        return new OpenAiAudioSpeechModel(audioApi);
    }

    @Bean
    public OpenAiAudioTranscriptionModel openAiAudioTranscriptionModel(){
        OpenAiAudioApi audioApi = new OpenAiAudioApi(baseUrl, apiKey, RestClient.builder(), WebClient.builder(), RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER);
        return new OpenAiAudioTranscriptionModel(audioApi);
    }
}
